﻿
using Microsoft.WindowsAzure.Storage.Blob;
using System.Diagnostics;
using System.IO;

namespace EmperialApps.WeatherSpark.Service.Internal {

    /// <summary>Reports capacity updates to the underlying memory stream.</summary>
    internal sealed class MonitoredMemoryStream : MemoryStream {
        private const int Granularity = 1024;
        private readonly string _name;

        /// <summary>Initializes a new instance of the <see cref="MonitoredMemoryStream"/> class with the specified name.</summary>
        public MonitoredMemoryStream( string name ) { this._name = name; }

        /// <inheritdoc/>
        public override int Capacity {
            get { return base.Capacity; }
            set {
                int monitoredCapacity = base.Capacity / Granularity;
                int monitoredValue = value / Granularity;
                if( monitoredValue > monitoredCapacity )
                    TraceEventType.Information.Trace( "Updating {0} capacity to {1:0.0}KiB", this._name, value / 1024.0 );

                base.Capacity = value;
            }
        }

        public void SaveToBlob( CloudBlockBlob blob ) {
            this.Position = 0;
            blob.UploadFromStream( this );
        }
    }

}
